import time
from odoo import fields, models, api
from odoo.exceptions import UserError
from ...api.encapsulate.carriers import Carriers


class SyncRoute(models.TransientModel):
    _inherit = "sync.route"
    
    third_type = fields.Selection(selection_add=[("shippypro", "shippypro")])
    
    # 创建/更新第三方邮路
    def create_update_third_route(self, route_name, cts, courier, third_route_id, current_timestamp):
        third_route_id = third_route_id.filtered(lambda x:x.name == route_name)
        if third_route_id:
            third_route_id.write({
                'label': cts['Label'],
                'route_logo': cts['CarrierLogo'],
                'update_time_stamp': current_timestamp,
                'active': True,
            })
        else:
            third_route_id.create({
                'name': route_name,
                'route_id': cts['CarrierID'],
                'courier_id': courier.id,
                'third_type': 'shippypro',
                'label': cts['Label'],
                'route_logo': cts['CarrierLogo'],
                'update_time_stamp': current_timestamp,
                'active': True,
            })
    
    # shippypro同步邮路
    def action_syn_route(self):
        if self.third_type == 'shippypro':
            route_collect = self.env['rp.third.route.collect']
            current_timestamp = time.time()
            carriers_dict = Carriers.get_carriers()  # 调用接口
            # 1、获取承运商邮路
            for courier_name, courier_contents in carriers_dict["Carriers"].items():
                courier = route_collect.courier_deal(courier_name)
                # 2、创建/修改承运商邮路
                for cts in courier_contents:
                    third_route_id = route_collect.search([('route_id', '=', cts['CarrierID']),
                                                           ('courier_id', '=', courier.id),
                                                           ('third_type', '=', 'shippypro'),
                                                           ('active', 'in', [True, False])])
                    # 单一邮路的情况
                    if cts['CarrierService'] and cts['CarrierService'] != 'All Services':
                        self.create_update_third_route(route_name=cts['CarrierService'], cts=cts, courier=courier, third_route_id=third_route_id, current_timestamp=current_timestamp)
                    # 全部邮路的情况
                    else:
                        for route_name in cts['ServicesList']:
                            self.create_update_third_route(route_name=route_name, cts=cts, courier=courier, third_route_id=third_route_id, current_timestamp=current_timestamp)
            # 3、归档没有修改过的邮路
            absent_route_ids = route_collect.search([('update_time_stamp', '!=', current_timestamp),
                                                     ('third_type', '=', 'shippypro')])
            for route_id in absent_route_ids:
                route_id.write({
                    'active': False
                })
            actions = self.env['ir.actions.act_window'].search([('res_model', '=', 'rp.third.route.collect')], limit=1)
            actions['target'] = 'main'
            return actions.read()[0]
